package com.yby6.led.test;

import java.io.File;
import java.io.IOException;
import java.util.Set;

import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.RmCommand;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class GitUtil {
	
	//定义本地git下来的项目地址
    public static final String LOCALPATH = "F:/项目demo/git-pmd/";
    //.git文件路径 读取.git文件夹
    public static final String LOCALGITFILE = LOCALPATH + ".git";
    
    /*LOCALGITFILE 地址表示你在 gitee 或者 hub 当中创建的某个仓库 用这个仓库来进行提交git记录*/
    
    //gitee邮箱
    public static final String USER = "1692700664@qq.com";
    //gitee密码
    public static final String PASSWORD = "yby123..";
    //推送注释
    public static final String message ="linuxdo-yangbuyiya@YBY6.com";

    
    public static boolean commitFiles() {
        try (Git git = Git.open(new File(LOCALGITFILE))) {
            // Add all changes including new files and modifications
            git.add().addFilepattern(".").call();
            
            // Handle deleted files
            Status status = git.status().call();
            handleRemovedFiles(git, status.getMissing());
            handleRemovedFiles(git, status.getRemoved());
            
            // Commit changes
            git.commit().setMessage(message).call();
            
            // Push changes
            git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER, PASSWORD)).call();
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    private static void handleRemovedFiles(Git git, Set<String> files) throws Exception {
        if (!files.isEmpty()) {
            RmCommand rmCommand = git.rm();
            for (String file : files) {
                System.err.println("Handling removed file: " + file);
                rmCommand.addFilepattern(file).call();
            }
        }
    }
    
    public static void main(String[] args) {
        boolean result = commitFiles();
        System.out.println("Commit result: " + result);
    }
}
